package com.by.consumer;

import com.by.bean.Order;
import com.by.bean.OrderDetail;
import com.by.config.Constant;
import com.by.config.RabbitUtils;
import com.by.config.RedisUtils;
import com.by.service.OrderService;
import com.by.service.impl.OrderType;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class OrderConsumer {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    OrderService orderService;

    @Autowired
    RabbitUtils rabbitUtils;

    /**
     * 监听订单队列 用于生成订单
     * @param message
     */
    @RabbitListener(queues = {Constant.ORDER_QUEUE})
    public void handlerOrder(Message message, Channel channel){
        handlerConsumer(message,channel);
    }

    @RabbitListener(queues = {Constant.ORDER_QUEUE})
    public void handlerOrder2(Message message, Channel channel){
        handlerConsumer(message,channel);
    }


    private void handlerConsumer(Message message, Channel channel){
        String msg = new String(message.getBody());
        //队列中有 msg=userId:id
        String[] gdt = msg.split(":");
        int userId = Integer.parseInt(gdt[0]);
        int goodId = Integer.parseInt(gdt[1]);
        //生成订单(商品信息:1.从redis取 2.生成订单时 从数据库查)
        //获取订单及明细相关数据 生成订单
        //调用生成订单的业务逻辑
        //取商品信息
        int num = 1;
        String name = redisUtils.get("goods:"+goodId+":name");
        double price = Double.parseDouble(redisUtils.get("goods:"+goodId+":price"));
        //定义订单
        Order order = new Order();
        order.setPayable(price);
        order.setMoney(price);
        order.setUserId(userId);
        order.setType(OrderType.SECOND_KILL);

        //定义订单明细
        OrderDetail detail = new OrderDetail();
        detail.setNum(num);
        detail.setPrice(price);
        detail.setName(name);
        detail.setGoodsId(goodId);
        List<OrderDetail> list = new ArrayList<>();
        list.add(detail);
        order.setOrderDetails(list);
        //为了避免重复消费  根据用户id和商品id查询是否有订单记录，如果有，说明已经生成 直接忽略以下的业务，没有 再继续
        //2.以用户id:商品id为key 如果redis不存在 保存
        boolean flag = redisUtils.setNx(msg,"yes");
        if (!flag){
            //说明用户已生成过订单 直接忽略
            return;
        }

        int rs = orderService.save(order);
        if (rs==0){
            log.error("用户["+userId+"]抢购商品["+goodId+"]生成订单失败");
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else if (rs>0) {
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 使用mq延迟队列 记录订单30秒未支付 更新订单状态
            rabbitUtils.sendLazyMsg(rs+"",30000);
        }
    }

    @RabbitListener(queues = {Constant.LAZY_QUEUE})
    public void handlerLazyOrder(Message message){
        //订单id
        String id = new String(message.getBody());
        //根据订单id判断订单状态 如果未支付 取消订单  根据订单id查询对应商品id 将对应商品数量+1

    }
}
